﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Halfpipe.Data.Service;
using HalfpipeDemo.Data.Service;

namespace HalfpipeDemo.Web.Controllers
{
    // TODO: This is a temporary kludge. Replace with MVC 3 DI when this demo is updated to MVC 3.
    public class HalfpipeDemoControllerFactory : DefaultControllerFactory
    {
        private static readonly object UnitOfWorkKey = new Object();

        private static INorthwindUnitOfWork GetUnitOfWork(RequestContext requestContext)
        {
            INorthwindUnitOfWork result = (INorthwindUnitOfWork)requestContext.HttpContext.Items[UnitOfWorkKey];
            if (result == null)
            {
                result = new NorthwindUnitOfWork();
                requestContext.HttpContext.Items[UnitOfWorkKey] = result;
            }
            return result;
        }

        private static void ReleaseUnitOfWork(RequestContext requestContext)
        {
            IUnitOfWork uow = (IUnitOfWork)requestContext.HttpContext.Items[UnitOfWorkKey];
            if (uow != null)
            {
                uow.Dispose();
                requestContext.HttpContext.Items[UnitOfWorkKey] = null;
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification="This is done, but FxCop can't see the reference in HttpContext.")]
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == typeof(EmployeeController))
            {
                return new EmployeeController(GetUnitOfWork(requestContext));
            }
            return base.GetControllerInstance(requestContext, controllerType);
        }

        public override void ReleaseController(IController controller)
        {
            var ec = controller as EmployeeController;
            if (ec != null)
            {
                RequestContext rc = ec.ControllerContext.RequestContext;
                ReleaseUnitOfWork(rc);
            }
            base.ReleaseController(controller);
        }        
    }
}